package com.foreveross.eimpc.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class LoginFilter implements javax.servlet.Filter {
	public LoginFilter() {
	}
	 private  Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	private FilterConfig config;

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		
		String fromUrl = request.getRequestURI();
		int index = fromUrl.lastIndexOf('.');
		if(index!=-1){
			String suffix = fromUrl.substring(index,fromUrl.length());
			if(ingone(suffix)){
				chain.doFilter(request, response);
				return;
			}
		}
	
		String ingonegpath = config.getInitParameter("ingonegpath");
		String[]  paths = ingonegpath.split(";");
		for(int i=0;i<paths.length;i++){
			String path = request.getContextPath()+paths[i];
			if(path.equals(fromUrl)){
				chain.doFilter(request, response);
				return;
			}
		}
		
		HttpSession session = request.getSession(true);
		JSONObject user = (JSONObject)session.getAttribute("user");
		boolean isLogin = user!=null?user.getBooleanValue("login"):false;
		if(!isLogin){
			logger.info("session invalidate...");
			HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(
					(HttpServletResponse) response);
			String reLogUrl = request.getContextPath() + "/index.jsp";
			wrapper.sendRedirect(reLogUrl);
		}else{
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) {
		this.config = filterConfig;
	}

	public void destroy() {
		this.config = null;
	}
	
	private boolean ingone(String suffi){
		boolean isIngone = false;
		if(".jpg".equalsIgnoreCase(suffi)){
			isIngone = true;
		}
		if(".css".equalsIgnoreCase(suffi)){
			isIngone = true;
		}
		return isIngone;
	}
	public static void main(String[] args){
		String str = "aaa.jpg";
		str = str.substring(str.lastIndexOf('.'),str.length());
		System.out.println(str);
	}
}